//
//  XJAllOrderViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/26.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  全部订单

#import "XJAllOrderViewController.h"
#import "XJPayViewController.h"
#import "XJAfterSaleViewController.h" //申请售后
#import "XJCommentViewController.h" // 立即评价
#import "XJOrderDetailViewController.h" // 订单详情



//View
#import "XJMyOrderCell.h"
#import "XJMyOrderSectionHeaerView.h"
#import "XJMyOrderSectionFooterView.h"

// 刷新加载
#import "RBRefreshHeader.h"
#import "RBRefreshFooter.h"
#import "RBNoDataView.h"

//model
#import "XJMyOrderBigModel.h"

@interface XJAllOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger _page;
}
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray <XJMyOrderBigModel *>*orderArray;
@property(nonatomic, strong) RBNoDataView *nodataView;



@end

@implementation XJAllOrderViewController
#pragma mark - 一 lazy
- (UITableView *)tableView {
    if (!_tableView) {
        
        // 如果是iphoneX的话 tableView 的高度 = 屏高 - 顶部导航64 - 底部状态栏 34
        // √https://github.com/coderketao/iOS11-iPhoneX
        CGFloat kHT_TabbarSafeBottomMargin = 0;
        if (KHeight > 667) {
            kHT_TabbarSafeBottomMargin = 34;
        }
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - XJTopNavH - kHT_TabbarSafeBottomMargin) style:(UITableViewStylePlain)];
        [_tableView registerClass:[XJMyOrderCell class] forCellReuseIdentifier:@"XJMyOrderCellId"];
        [_tableView registerClass:[XJMyOrderSectionHeaerView class] forHeaderFooterViewReuseIdentifier:@"XJMyOrderSectionHeaerViewId"];
        [_tableView registerClass:[XJMyOrderSectionFooterView class] forHeaderFooterViewReuseIdentifier:@"XJMyOrderSectionFooterViewId"];
        
        _tableView.rowHeight = 120;
        _tableView.sectionHeaderHeight = 40;
        _tableView.sectionFooterHeight = 100;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (NSMutableArray *)orderArray {
    if (!_orderArray) {
        _orderArray = [NSMutableArray array];
    }
    return _orderArray;
}

- (RBNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [RBNoDataView new];
    }
    return _nodataView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];
    
    [self requestAllData];
    
    [self setupRefresh];
}

- (void)setupView {
    self.navTitle = @"全部订单";
    [self.view addSubview:self.tableView];
}

- (void)setupRefresh {
    
    _page = 1;
    
    // 下拉刷新
    RBRefreshHeader *header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestAllData)];
    self.tableView.mj_header = header;
//    [self.tableView.mj_header beginRefreshing];
    
    RBRefreshFooter *footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
    self.tableView.mj_footer = footer;
}


#pragma mark - 二: UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.orderArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // 先取出     self.orderArray.count 中的大
    XJMyOrderBigModel *bigModel = self.orderArray[section];
    return bigModel.goods.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XJMyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XJMyOrderCellId"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 赋值
    XJMyOrderBigModel *bigModel = self.orderArray[indexPath.section];
    
    XJMyOrderGoodsModel *goodsModel = bigModel.goods[indexPath.row];
    
    NSString *imgStr = goodsModel.cover;
    NSString *name = goodsModel.goods_name;
    NSString *price = goodsModel.price;
    NSString *count = goodsModel.quantity;
    
    [cell configureXJMyOrderCellWithImgStr:imgStr name:name price:price count:count];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    XJMyOrderSectionHeaerView *sectionHeaderV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJMyOrderSectionHeaerViewId"];
    
    XJMyOrderBigModel *bigModel = self.orderArray[section];
    
    [sectionHeaderV configureMyOrderSectionHeaderViewShopName:bigModel.shop_name rightTitle:bigModel.state_name];

    return sectionHeaderV;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    XJMyOrderSectionFooterView *sectionFooterView =  [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJMyOrderSectionFooterViewId"];
    
    XJMyOrderBigModel *bigModel = self.orderArray[section];
    
    [sectionFooterView configureXJMyOrderSectionFooterViewCount:bigModel.goods_count price:bigModel.order_amount freight:bigModel.express_amount bntArray:bigModel.btns];
    
    
    XJWeakSelf(self);
    sectionFooterView.myOrderSectionFooterViewFirstButtonBlock = ^(XJMyOrderBtnModel *btnModel) {
        if ([btnModel.code isEqualToString:kOrderBtnPay]) {
            XJLog(@"立即付款");
            XJPayViewController *payVC = [[XJPayViewController alloc] init];
            
            // 请求参数
            payVC.foreign_infos = bigModel.order_sn;
            payVC.order_amount = bigModel.order_amount;
            payVC.order_type = @"2";
            
            [weakself.navigationController pushViewController:payVC animated:YES];
        }else if ([btnModel.code isEqualToString:kOrderBtnRefund]) {
            XJLog(@"申请售后");
            
            XJAfterSaleViewController *afterSaleVC = [[XJAfterSaleViewController alloc] init];
            afterSaleVC.order_goods_id = [bigModel.goods firstObject].goods_id;
            afterSaleVC.orderSN = bigModel.order_sn;
            [self.navigationController pushViewController:afterSaleVC animated:YES];
            
        }else {
            XJLog(@"%@",btnModel);
        }
    };
    
    sectionFooterView.myOrderSectionFooterViewSecondButtonBlock = ^(XJMyOrderBtnModel *btnModel) {
//        [weakself requestDeleteOrderWithBigModel:bigModel];

        if ([btnModel.code isEqualToString:kOrderBtnCancel]) {
            
            XJLog(@"取消订单");
            [self requestCancelOrderWithBigModel:bigModel];
            
        }else if ([btnModel.code isEqualToString:kOrderBtnReceive]){
            
            XJLog(@"确认收货");
            [self requestReceiveWithBigModel:bigModel];
            
        }else if([btnModel.code isEqualToString:kOrderBtnDelete]){
            
            XJLog(@"删除订单");
            [self requestDeleteOrderWithBigModel:bigModel];
            
        }else if ([btnModel.code isEqualToString:kOrderBtnComment]){
            
            XJLog(@"立即评价");
            XJCommentViewController *commentVC = [[XJCommentViewController alloc] init];
            commentVC.order_goods_id = [bigModel.goods firstObject].goods_id;
            commentVC.orderSN = bigModel.order_sn;
            
            [self.navigationController pushViewController:commentVC animated:YES];

        }else {
            
            XJLog(@"%@",btnModel);
            
        }    
    };
   
    return sectionFooterView;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    XJOrderDetailViewController *orderDetailVC = [[XJOrderDetailViewController alloc] init];
    
    //请求参数
    XJMyOrderBigModel *bigM = self.orderArray[indexPath.section];
    orderDetailVC.orderSN = bigM.order_sn;
    
    orderDetailVC.orderDetailType = XJOrderDetailTypeFinish;
    [self.navigationController pushViewController:orderDetailVC animated:YES];
}

#pragma mark - 让tableView的sectionHeader 随cell一起移动
//https://www.jianshu.com/p/264bd4d33c7f
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (self.tableView == scrollView) {
        CGFloat sectionHeaderHeight =  40;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

#pragma mark - 三 网络请求
/**
 请求数据
 上拉加载 下拉刷新。
 */
//请求全部订单信息
- (void)requestAllData {
    XJLog(@"下拉刷新");
    _page = 1;
    
    //解决bug:最后一个数据删除不掉。 有没有全部清空
    [self.orderArray removeAllObjects];

    //0为全部
    [XJHttpTool requestOrderOrderListsWithType:@"0" page:@"1" successH:^(id responseObjc) {
        
        [self.tableView.mj_header endRefreshing];
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if([code isEqualToString:@"0"]){
            
            NSArray *orders = responseObjc[@"data"][@"content"][@"order"];
            if (orders.count) {
                self.orderArray =  [XJMyOrderBigModel mj_objectArrayWithKeyValuesArray:orders];
                [self.nodataView rb_hideNoDataView];
            }else {
                [self.nodataView rb_showNoDataViewInView:self.tableView message:@"没有数据" placeHolder:@"暂无数据.png"];
            }
        
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            
        }else{
            XJLog(@"出错了:%@",responseObjc);
        }
        
    } failH:^(NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        
        [JRToast showWithText:[error localizedDescription]];
    }];
}


- (void)requestMoreData {
    XJLog(@"上拉加载");
    
    _page++;
    
    
    NSString *pageStr = [NSString stringWithFormat:@"%ld",_page];
    
    [XJHttpTool requestOrderOrderListsWithType:@"0" page:pageStr successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSArray *orderArr = responseObjc[@"data"][@"content"][@"order"];
            
            if (orderArr.count) {
                NSArray *modelArr = [XJMyOrderBigModel mj_objectArrayWithKeyValuesArray:orderArr];
                [self.orderArray addObjectsFromArray:modelArr];
                [self.tableView.mj_footer endRefreshing];

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.tableView reloadData];
                });
            }else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    } failH:^(NSError *error) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}


//删除订单网络请求
- (void)requestDeleteOrderWithBigModel:(XJMyOrderBigModel *)bigmodel {

    
    [XJHttpTool requestOrderDeleteOrderWithOrderSN:bigmodel.order_sn successH:^(id responseObjc) {
        XJLog(@"删除成功:%@",responseObjc);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            [self requestAllData];
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        
        [JRToast showWithText:[error localizedDescription]];
        
    }];
}

//取消订单网络请求
- (void)requestCancelOrderWithBigModel:(XJMyOrderBigModel *)bigM{
    
    [XJHttpTool requestOrderCancelOrderWithOrderNum:bigM.order_sn successH:^(id responseObjc) {
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            XJLog(@"取消成功");
            
            [self requestAllData];
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

//确认收货
- (void)requestReceiveWithBigModel:(XJMyOrderBigModel *)bigM {
    [XJHttpTool requestOrderReceiveWithOrderSN:bigM.order_sn successH:^(id responseObjc) {
        
        [self requestAllData];
        
    } failH:^(NSError *error) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
